import { ca } from 'element-plus/es/locales.mjs';
import localforage from 'localforage';

// 初始化数据库
const initDB = async () => {
  localforage.config({
    name: 'ResumeGeneratorDB',
    storeName: 'userData',
    version: 1.0
  });
};

// 用户数据操作
const userDB = {
  saveProfile: async (profile) => {
    await localforage.setItem('profile', profile);
  },
  getProfile: async () => {
    return await localforage.getItem('profile');
  }
};

// 草稿数据操作
const draftDB = {
  saveDraft: async (draft) => {    
    const drafts = await localforage.getItem('drafts') || [];
    drafts.push(draft);
    // console.log("set drafts:",drafts);
    try{
      await localforage.setItem('drafts', JSON.parse(JSON.stringify(drafts)));
    }catch(e){
      console.log("set item error:",e);
    }
  },
  getDrafts: async () => {
    return await localforage.getItem('drafts') || [];
  },
  deleteDraft: async (draftId) => {
    // console.log("draftDB.deleteDraft");
    
    const drafts = await localforage.getItem('drafts') || [];
    const updatedDrafts = drafts.filter(d => d.id !== draftId);
    await localforage.setItem('drafts', updatedDrafts);
  }
};

export { initDB, userDB, draftDB };
